﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;

namespace SearchBackEnd
{
    /// <summary>
    /// Container for the main method of the back-end server.
    /// Here we create the service host that will enable receiving
    /// requests from the front end server and we register the back-end server in the front-end server.
    /// </summary>
    class BackEndServer
    {
        /// <summary>
        /// Back end server main.
        /// </summary>
        /// <param name="args">
        /// contain 2 strings:
        /// 1) the port of the back-end server.
        /// 2) the partial URI of the front-end server.
        /// </param>
        public static void Main(String[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("Bad arguments!");
                Console.WriteLine("Usage: SearchBackHost.exe <port> <front end partial URI>");
                return;
            }
            string uriString = "net.tcp://localhost:" + args[0] + "/Services";
            Console.Write("Starting server... ");
            ServiceHost backEndHost = new ServiceHost(typeof(SearchBackend), new Uri(uriString));
            ((NetTcpBinding)backEndHost.Description.Endpoints[0].Binding).Security.Mode = SecurityMode.None;
            backEndHost.Open();
            Console.WriteLine("Done!");

            SearchRegistryClient searchRegistryClient = new SearchRegistryClient(
                                                                   "NetTcpBinding_ISearchRegistry",
                                                                   "net.tcp://" + args[1]
                                                                   );

            uriString = "net.tcp://" + System.Net.Dns.GetHostName() + ":" + args[0] + "/Services/SearchBackEnd";
            Uri myUri = new Uri(uriString);
            Console.Write("Adding server to server registry... ");
            try
            {
                searchRegistryClient.AddBackEndServer(myUri);
            }
            catch (Exception e)
            {
                Console.WriteLine("Can't register in the front end server - " + e.Message);
                backEndHost.Close();
                return;
            }

            Console.WriteLine("Done!");
            Console.WriteLine("Server up and running");
            Console.WriteLine("Press the enter key to stop server.");
            Console.ReadLine();
            try
            {
                searchRegistryClient.RemoveBackEndServer(myUri);
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to remove this server from the front-end's servers list - " + e.Message);
            }
            backEndHost.Close();
            Console.WriteLine("Server closed");
        }
    }
}
